<?php

namespace app\admin\controller\yiliao;

use app\common\controller\Backend;
use think\Db;
use EasyWeChat\Factory;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\yiliao\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\yiliao\Order;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function add()
    {
        return;
    }
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                if ($item['status']!=0) {
                    throw new \think\Exception("只能删除未支付订单");
                } else {
                    $count += $item->delete();
                }
            }
            Db::commit();
        } catch (\think\exception\PDOException|\think\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            //状态:0=待付款,1=待服务,2=已完成,3=退款中,4=已退款
            if ($row['status']==4) {
                throw new \think\Exception("已退款禁止编辑");
            } elseif ($params['status']==4) {
				if ($row['status']==1||$row['status']==3) {
					$setting = get_addon_config('yiliao');
					$epay = get_addon_config('epay');
					$document_root = request()->server("DOCUMENT_ROOT").'/..';
					//退款处理
					$config = [
						// 必要配置
						'app_id'             => $epay['wechat']['miniapp_id'],
						'mch_id'             => $epay['wechat']['mch_id'],
						'key'                => $epay['wechat']['key'],   // API v2 密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)
					
						// 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
						'cert_path'          => $document_root.$epay['wechat']['cert_client'], // XXX: 绝对路径！！！！
						'key_path'           => $document_root.$epay['wechat']['cert_key'],      // XXX: 绝对路径！！！！
					
						'notify_url'         => '',     // 你也可以在下单时单独设置来想覆盖它
					];
				   
					$app = Factory::payment($config);
					
					// 参数分别为：商户订单号、商户退款单号、订单金额、退款金额、其他参数
					$refundorderid = date("YmdHis").rand(100, 999);
					$ret = $app->refund->byOutTradeNumber($row['orderid'], $refundorderid, $row['total']*100, $row['total']*100, [
						'refund_desc' => '订单号:'.$row['orderid'],
					]);
					if ($ret['result_code']=="SUCCESS") {
						$params['refund']=$refundorderid;
					} else {
						throw new \think\Exception("错误:".$ret['err_code_des']);
					}
				} else {
					$this->error("禁止退款");
				}
               
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (\think\exception\ValidateException|\think\exception\PDOException|\think\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
}
